package com.qishao.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qishao.execl.ExeclSubject;
import com.qishao.model.EduSubject;
import com.qishao.service.EduSubjectService;
import com.qishao.service_base.error.CustomException;

/**
 * 课程分类导入 监听器
 *
 * */
public class ExeclSubjectListener extends AnalysisEventListener<ExeclSubject> {

    private EduSubjectService subjectService;

    public ExeclSubjectListener() {
    }

    public ExeclSubjectListener(EduSubjectService subjectService) {
        this.subjectService = subjectService;
    }

    /**
     * 一行一行的读取Execl文件中的数据
     * */
    @Override
    public void invoke(ExeclSubject execlSubject, AnalysisContext analysisContext) {
        String onesubjectName = execlSubject.getOneSubjectName();
        if(null == execlSubject){
            throw new CustomException("20001","Execl文件中数据为空，请填写后再执行！");
        }

        //校验文数据中的一级分类是否 已经在数据库表中存在
        EduSubject eduOneSubject = chechOneSubjectName(onesubjectName);
        if(null == eduOneSubject){
            eduOneSubject = new EduSubject();
            eduOneSubject.setTitle(onesubjectName);
            eduOneSubject.setParentId("0");
            subjectService.save(eduOneSubject);
        }

        String id = eduOneSubject.getId();

        //校验文数据中的二级分类是否已经在数据库表中存在
        String twoSubjectName = execlSubject.getTwoSubjectName();

        EduSubject eduTwoSubject = chechTwoSubjectName(twoSubjectName,id);
        if(null == eduTwoSubject){
            eduTwoSubject = new EduSubject();
            eduTwoSubject.setTitle(twoSubjectName);
            eduTwoSubject.setParentId(id);
            subjectService.save(eduTwoSubject);
        }
    }

    /**
     * 校验文数据中的一级分类是否已经在数据库表中存在
     * */
    private EduSubject chechOneSubjectName(String oneSubjectName) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("title",oneSubjectName);
        wrapper.eq("parent_id","0");
        EduSubject subject = subjectService.getOne(wrapper);
        return subject;
    }

    /**
     * 校验文数据中的二级分类是否已经在数据库表中存在
     * */
    private EduSubject chechTwoSubjectName(String twoSubjectName,String parentId) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("title",twoSubjectName);
        wrapper.eq("parent_id",parentId);
        EduSubject subject = subjectService.getOne(wrapper);
        return subject;
    }


    /**
     * 读取完后执行
     * */
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
